package com.cincc.cinccimdemo.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.cincc.cinccimdemo.R;
import com.cincc.cinccimdemo.common.callback.OnItemClickListener;
import com.cincc.im.table.IMContactUser;

import java.util.List;

public class SearchUserAdapter extends RecyclerView.Adapter<SearchUserAdapter.MyViewHolder> {

    Context mContext;
    private final List<IMContactUser> mList;

    public SearchUserAdapter(Context mContext, List<IMContactUser> mList) {
        this.mContext = mContext;
        this.mList = mList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.list_contact_my_friend_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        IMContactUser model = mList.get(position);

        holder.nameText.setText(model.nickName);
        holder.firstTv.setVisibility(TextUtils.isEmpty(model.protraitUrl) ? View.VISIBLE : View.GONE);
        holder.avatar.setVisibility(TextUtils.isEmpty(model.protraitUrl) ? View.GONE : View.VISIBLE);
        if (TextUtils.isEmpty(model.protraitUrl)) {
            holder.firstTv.setText(model.nickName.substring(0, 1));
        } else {
            Glide.with(mContext).load(model.protraitUrl).placeholder(R.mipmap.avatar_def)
                    .transforms(new CenterCrop(), new RoundedCorners(15))
                    .into(holder.avatar);
        }
        holder.headerTv.setVisibility(View.GONE);

        holder.itemView.setOnClickListener(view -> onItemClickListener.onClick(position));
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView firstTv;
        TextView nameText;
        TextView headerTv;
        ImageView avatar;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            firstTv = itemView.findViewById(R.id.first_letter_tv);
            nameText = itemView.findViewById(R.id.mText_item_contact_name);
            headerTv = itemView.findViewById(R.id.mText_list_item_header);
            avatar = itemView.findViewById(R.id.img_avatar);
        }
    }
}
